<?php

namespace support\Service;

use support\Db;
use support\Exception\ApiException;
use support\Model\MemberAccountModel;
use support\Model\MemberBalanceLog;

class MemberBalanceLogService extends BaseService
{

    public function __construct()
    {
        self::$model = new MemberBalanceLog();
    }


    /**
     * 用户变动金额
     * @param $member_id
     * @param $type 1:购买消耗  2:退款退回 3:后台增加 4后台减少 5:充值'
     * @param $io 1  增加  2 减少
     * @param $balance  金额
     * @param $remark   备注
     * @param $order_id 订单ID
     * @param $order_no  订单号
     * @return void
     */
    public static function changeMemberMoney(
        $member_id,
        $type,
        $io,
        $balance,
        $remark = '',
        $order_id = 0,
        $order_no = ''
    )
    {
        $memberAccountModel = new MemberAccountModel();
        $member_info = MemberService::info($member_id);
        if (!$member_info) {
            throw   new ApiException('用户不存在');
        }
        $member_account_info = MemberAccountService::getAccountInfo($member_id);
        //判断用户余额是否充足
        if ($io == 2 && $member_account_info['balance'] < $balance) {
            throw   new ApiException('用户余额不足');
        }
        $before_balance = $member_account_info['balance'];
        $after_balance = $io == 1 ? $member_account_info['balance'] + $balance : $member_account_info['balance'] - $balance;
        Db::beginTransaction();
        try {
            self::init(
                $io,
                $type,
                $member_id,
                $before_balance,
                $io == 1 ? $balance : (0 - $balance),
                $after_balance,
                $remark,
                $order_id,
                $order_no
            );
            if ($io == 1) {
                $memberAccountModel->where('member_id', $member_id)->increment('balance', $balance);
            } else {
                $memberAccountModel->where('member_id', $member_id)->decrement('balance', $balance);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new ApiException($e->getMessage());
        }

    }

    public static function init($io, $type, $member_id, $before_balance, $balance, $after_balance, $remark = '', $order_id = 0, $order_no = '')
    {
        $data = [
            'io' => $io,
            'type' => $type,
            'member_id' => $member_id,
            'before_balance' => $before_balance,
            'balance' => $balance,
            'after_balance' => $after_balance,
            'remark' => $remark,
            'order_id' => $order_id,
            'order_no' => $order_no,
        ];
        return self::$model->insertOne($data);
    }
}
